#ifndef Motor_Control_Panel_H
#define Motor_Control_Panel_H

#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QComboBox>
#include <QSpinBox>
#include <QGroupBox>
#include <functional>
#include <QCheckBox>
#include <QDockWidget>
#include <qlistwidget.h>
#include "../Device_Motor/Device_Motor.h"
#include "../Device_Motor/Device_Motor_Factory.h"
#include "CoordinateTransformStrategy.h"
#include "BeamQualityAnalysis.h"
#include "PositionConfigDialog.h"
#include "RayCiPro_C.h"
#include "../LiveMode/LiveMode_Analysis.h"

class Device_Motor_FuYu;

class Motor_Control_Panel : public QDockWidget
{
    Q_OBJECT

public:
    enum AutoScanState {
        Idle,
        Homing,
        Scanning
    };

    explicit Motor_Control_Panel(QWidget *parent = nullptr);
    ~Motor_Control_Panel() override;
    bool isMotorConnected() const;
    void MoveAbsolute(double absolute=0);
    void MoveRelative(double relative=0);
    void Motorstop();
    bool HasPresetPosition() const;
    void ShowPresetWidget();
    void MotorHome();
    void MotorConnect();
    void setBeamQualityFrameRate(int frameRate);
    bool calculateAutoBeamQualityPositions();
    bool startAutoScanProcess();
    void stopAutoScanProcess();
    bool isAutoScanRunning() const { return m_autoScanState != AutoScanState::Idle; }
    void setWavelength(double wavelength);
    void setupUI();
    QList<double> getPresetPositions() const;
    void setScanCompletedCallback(const std::function<void(bool)> &callback) {
        m_scanCompletedCallback = callback;
    }

    LiveMode_Analysis *liveModeAnalysis = nullptr;

signals:
    void positionChanged(double position,bool isshow=true);
    void positionUpdated(double position);
    void StartAutoMeasurement();
    void autoScanCompleted(bool success);

private slots:
    void onDisconnectClicked();
    void onMoveToClicked();
    void onMoveRelativeClicked();
    void onConnectClicked();
    void onHomeClicked();
    void onStopClicked();
    void onScanDataCollection();

    // 预设位置管理相关槽函数
    void onConfigurePositionClicked();
    void onMoveToPresetClicked();
    void onSequentialMoveClicked();
    void onPresetSelectionChanged();
    void onPresetDoubleClicked(QListWidgetItem *item);
    void onSequentialMoveTimer();
    void onStatusMonitorTimer();

private:
    std::function<void(bool)> m_scanCompletedCallback;

    // 速度和加速度设置
    void onSetSpeedClicked();
    void onSetAccelerationClicked();
    void onSetDecelerationClicked();
    void onSetHomeParameters();

    // 更新UI
    void updateStatus();

    void setupConnectionGroup(QGroupBox *group);
    void setupMovementGroup(QGroupBox *group);
    void setupSpeedGroup(QGroupBox *group);
    void setupInterpolationGroup(QGroupBox *group);
    void setupIOGroup(QGroupBox *group);
    void setup485Group(QGroupBox *group);
    void setupPresetGroup(QGroupBox *group);

    // 辅助函数
    void updateUIState(bool connected);
    void showMessage(const QString &message);
    void disableUnsupportedFeatures();
    bool isMotorReadyForOperation() const;
    
    // 状态监控
    void startStatusMonitoring();
    void stopStatusMonitoring();



    // 连接设置
    QComboBox *m_motorTypeComboBox;
    QLineEdit *m_ipAddressEdit;
    QSpinBox *m_portSpinBox;
    QSpinBox *m_deviceIdSpinBox;
    QSpinBox *m_axisSpinBox;
    QPushButton *m_connectButton;
    QPushButton *m_disconnectButton;

    // 移动控制
    QDoubleSpinBox *m_positionSpinBox;
    QDoubleSpinBox *m_relativeDistanceSpinBox;
    QComboBox *m_motionModeComboBox;
    QPushButton *m_moveToButton;
    QPushButton *m_moveRelativeButton;
    QPushButton *m_homeButton;
    QPushButton *m_stopButton;
    QComboBox *m_homeDirectionComboBox;
    QComboBox *m_stopModeComboBox;

    // 速度和加速度设置
    QDoubleSpinBox *m_speedSpinBox;
    QDoubleSpinBox *m_accelerationSpinBox;
    QDoubleSpinBox *m_decelerationSpinBox;
    QPushButton *m_setSpeedButton;
    QPushButton *m_setAccelerationButton;
    QPushButton *m_setDecelerationButton;
    QDoubleSpinBox *m_homeSpeedSpinBox;
    QDoubleSpinBox *m_homeAccDecSpinBox;
    QDoubleSpinBox *m_homeFallStepSpinBox;


    // 插补控制
    QDoubleSpinBox *m_x2AxisSpinBox;
    QDoubleSpinBox *m_y2AxisSpinBox;
    QDoubleSpinBox *m_x3AxisSpinBox;
    QDoubleSpinBox *m_y3AxisSpinBox;
    QDoubleSpinBox *m_z3AxisSpinBox;
    QDoubleSpinBox *m_xArcSpinBox;
    QDoubleSpinBox *m_yArcSpinBox;
    QDoubleSpinBox *m_angleArcSpinBox;
    QPushButton *m_linearInterpolation2AxisButton;
    QPushButton *m_linearInterpolation3AxisButton;
    QPushButton *m_arcInterpolationButton;
    QPushButton *m_stopInterpolationButton;

    // IO控制
    QSpinBox *m_outputPortSpinBox;
    QSpinBox *m_outputValueSpinBox;
    QSpinBox *m_inputPortSpinBox;
    QLabel *m_inputValueLabel;
    QPushButton *m_setOutputButton;
    QPushButton *m_getInputButton;

    // 485通信
    QLineEdit *m_write485DataEdit;
    QLineEdit *m_read485DataEdit;
    QPushButton *m_write485DataButton;
    QPushButton *m_read485DataButton;

    // 状态显示
    QLabel *m_positionLabel;
    QLabel *m_speedLabel;
    QLabel *m_statusLabel;

    Device_Motor_FuYu* getFuYuMotor() const {
        if (m_motor && m_motor->GetMotorType() == MotorType::Device_Motor_FuYu) {
            return dynamic_cast<Device_Motor_FuYu*>(m_motor.get());
        }
        return nullptr;
    }
    int m_frameRate = 10;
    int _nBeamQualityDocId = 0;
    QLabel *m_messageLabel=nullptr;
    std::shared_ptr<Device_Motor> m_motor;
    std::unique_ptr<CoordinateTransformStrategy> m_coordinateStrategy=nullptr;
    // FuYu电机现在通过统一的m_motor接口管理
    std::unique_ptr<QTimer> m_messageTimer = nullptr;
    std::unique_ptr<QTimer> m_statusMonitorTimer = nullptr;  // 状态监控定时器
    MotorStatus m_lastMotorStatus = MotorStatus::Disconnected;  // 记录上次状态
    ScanConfiguration m_scanConfig=ScanConfiguration();

    // 位置管理相关
    QVector<double> m_presetPositions;  // 存储预设位置
    QListWidget *m_presetListWidget;    // 位置列表显示
    QPushButton *m_configurePositionButton;  // 配置位置按钮
    QPushButton *m_moveToPresetButton;      // 移动到选中位置按钮
    QPushButton *m_sequentialMoveButton;    // 顺序移动按钮
    QCheckBox *m_measurementModeCheckBox;   // 测量模式复选框
    bool m_isSequentialMoving = false;      // 是否正在顺序移动
    int m_currentPresetIndex = 0;           // 当前移动位置索引
    bool m_autoScanStopped = false;     // 扫描停止标志

    void updatePresetListDisplay();

    std::unique_ptr<BeamQualityAnalysis> m_beamQualityAnalysis=nullptr;

    double calculateMoveTime(double distance, double speed, double acceleration, double deceleration);

    AutoScanState m_autoScanState = Idle;
    std::unique_ptr<QTimer> m_scanDataCollectionTimer = nullptr;

};

#endif // Motor_Control_Panel_H